package com.jiangdong.craft.service.impl;

import com.jiangdong.craft.dto.ResponseDTO;
import com.jiangdong.craft.entity.Relation;
import com.jiangdong.craft.mapper.RelationMapper;
import com.jiangdong.craft.service.RelationService;
import com.jiangdong.craft.util.ResponseFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

@Service
public class RelationServiceImpl implements RelationService {

    @Autowired
    RelationMapper relationMapper;

    @Transactional(rollbackFor = RuntimeException.class)
    @Override
    public ResponseDTO add(Integer startId, Integer endId,Integer craftId) {
        Relation startRelation = new Relation();
        startRelation.setProcedureId(startId);
        startRelation.setPrepositionId(endId);
        startRelation.setCraftId(craftId);

        Relation endRelation = new Relation();
        endRelation.setProcedureId(endId);
        endRelation.setPostpostitionId(startId);
        endRelation.setCraftId(craftId);

        List<Relation> relations = new ArrayList<>();
        relations.add(startRelation);
        relations.add(endRelation);

        relationMapper.insertBatch(relations);

        return ResponseFactory.getResponse(null,"success");
    }

    @Transactional(rollbackFor = RuntimeException.class)
    @Override
    public ResponseDTO delRelationBetweenProcedure(Integer startId, Integer endId,Integer craftId) {
        List<Relation> relations = relationMapper.selectByExample(null);
        for (Relation relation : relations){
            if (relation.getProcedureId().equals(startId) && relation.getPrepositionId().equals(endId) && relation.getCraftId().equals(craftId)){
                relation.setPrepositionId(null);
                relationMapper.updateByPrimaryKey(relation);
                break;
            }
        }

        for (Relation relation : relations){
            if (relation.getProcedureId().equals(endId) && relation.getPostpostitionId().equals(startId)){
                relation.setPostpostitionId(null);
                relationMapper.updateByPrimaryKey(relation);
                break;
            }
        }

        return ResponseFactory.getResponse(null,"success");
    }

}
